<template>
  <div class="index-conntainer">
    <div class="content">
      
      <!-- 查询条件 -->
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item :label="t('product.name')" prop="name">
            <el-input
              v-model="queryParams.name"
              :placeholder="t('product.name')"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          
          <el-form-item v-if="isMerchandiser" :label="t('product.categoryId')" prop="categoryId" clearable>
            <el-select v-model="queryParams.categoryId"  :placeholder="t('common.choose')" size="small">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
          </el-form-item>
           
           
          
          <el-form-item>
            <el-button type="primary" @click="handleQuery()"><i-ep-search />{{ t('common.search') }}</el-button>
            <el-button @click="resetQuery()"><i-ep-refresh />{{ t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      
      <el-row :gutter="10" class="mb8">
           <el-col :span="1.5">
              <el-button
                 type="primary"
                 plain
                 :icon="Plus" 
                 v-if="isMerchandiser"
                 @click="handleAdd">{{ t('common.add') }}</el-button>
           </el-col>
           <el-col :span="1.5">
              <el-button
                 type="primary"
                 plain
                icon="icon-up-two"
                :disabled="multiple" 
                @click="handlerUp()"
                 v-if="isMerchandiser"
              >{{ t('common.up') }}</el-button>
           </el-col>
            
            <el-col :span="1.5">
               <el-button
                  type="warning"
                  plain
                 icon="icon-down-two"
                 :disabled="multiple" 
                 @click="handlerDown()"
                  v-if="isMerchandiser"
               >{{ t('common.down') }}</el-button>
            </el-col> 
       
         <el-col :span="1.5">
            <el-button
               type="success"
               plain
              icon="icon-file-excel"  
              @click="handlerExcel()"
            >{{ t('common.exportexcel') }}</el-button>
         </el-col>
         
        </el-row>
      
       <!--选项卡 -->
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="已上架" name="up"></el-tab-pane>
          <el-tab-pane label="未上架" name="down"></el-tab-pane>
      </el-tabs>
      
      
      <!--表格显示数据 -->
      <el-table ref="tableRef" v-loading="loading" :data="rows" @selection-change="handleSelectionChange"  @sort-change="tableSort">
          <el-table-column type="expand">
              <template #default="scope">
                <el-form   label-width="100px">
                  <el-row style="padding: 10px;">
                    <el-col :span="24">
                      <el-form-item   label="创建时间" >
                          {{scope.row.createTime}}
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item   label="商品描述" >
                          <div v-html="scope.row.description"></div>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24" v-if="scope.row.dishFlavors && scope.row.dishFlavors.length > 0">
                      <el-form-item   label="口味列表"  >
                          <div   class="flavorBox">

                            <!--商品本身有口味-->
                            <div   class="flavor">

                              <div v-for="(item ,index ) in scope.row.dishFlavors" class="cont">
                                <!--口味名称 -->
                                {{item.name}}

                                <!-- 口味明细 -->
                                <div class="labItems2"> 
                                  <DivItem v-for="(tag,ind) in item.value" :key="ind"  :value="tag.value" :money="tag.price"     >
                                   </DivItem>
                                </div>
                              </div>
                            </div>
                          </div>
                      </el-form-item>
                    </el-col>

                  </el-row>
                  </el-form>
                
              </template>
          </el-table-column>
        
           <el-table-column type="selection" width="55" align="center" />
           <el-table-column :label="t('common.id')" align="center" prop="id" width="80" />
           <el-table-column :label="t('merchand.name')" align="left" prop="merchantName" />
           <el-table-column :label="t('category.name')" align="left" prop="categoryName" />
           <el-table-column :label="t('product.name')" align="left" prop="name" />
           <el-table-column :label="t('product.price')" align="left" prop="price" v-if="isMerchandiser" sortable='custom'>
             <template #default="scope">
                <!-- 单个修改价格出现 -->
                <div v-if="showMoneyEdit[scope.$index]" class="float_left">
                    <el-input v-model="scope.row.price" type="number" size="small" style="width:120px" placeholder="请输入内容"></el-input>
                    <el-button type="primary" size="small"    @click="changeItemPrice(scope.row, scope.$index)">确定</el-button>
                    <el-button size="small" @click="showMoneyInput(scope.$index); "  >取消</el-button>
                </div>
                
                 <label v-else>
                    ¥ {{scope.row.price}} 
                    <el-icon :size="16" @click="showMoneyInput(scope.$index, scope.row.price)">
                      <EditPen />
                    </el-icon> 
                </label> 
             </template>  
           </el-table-column>
           
           <el-table-column :label="t('product.price')" align="left" prop="price" v-if="!isMerchandiser" sortable='custom'></el-table-column>
           
           <el-table-column :label="t('product.num')" align="left" prop="num"  v-if="isMerchandiser" sortable='custom'>
             <template #default="scope">
                  <!-- 单个修改出现 -->
                  <div v-if="showStockEdit[scope.$index]" class="float_left">
                      <el-input v-model="scope.row.num" type="number" size="small" style="width:120px" placeholder="请输入内容"></el-input>
                      <el-button type="primary" size="small"    @click="changeItemStock(scope.row, scope.$index)">确定</el-button>
                      <el-button size="small" @click="showStockInput(scope.$index); "  >取消</el-button>
                  </div>
                  
                   <label v-else>
                      <el-tag effect="dark" type="success" v-if="scope.row.num===-1">不限量</el-tag>
                      <el-tag effect="dark" v-else-if="scope.row.num>5">{{scope.row.num}} </el-tag>
                     
                      <el-tag  effect="dark"  type="danger" v-else>{{scope.row.num}}(库存不足)</el-tag>
                      
                      <el-icon :size="16" @click="showStockInput(scope.$index, scope.row.num)">
                        <EditPen />
                      </el-icon> 
                  </label> 
               </template>  
          </el-table-column>
          
          <el-table-column :label="t('product.num')" align="left" prop="num"  v-if="!isMerchandiser" sortable='custom'>
             <template #default="scope">                   
                   <label >
                      <el-tag effect="dark" type="success" v-if="scope.row.num===-1">不限量</el-tag>
                      <el-tag effect="dark" v-else-if="scope.row.num>5">{{scope.row.num}} </el-tag>                     
                      <el-tag  effect="dark"  type="danger" v-else>{{scope.row.num}}(库存不足)</el-tag>
                  </label> 
               </template>  
          </el-table-column>

           <el-table-column :label="t('product.picture')" align="center"  width="200">
            <template #default="scope">
               <img :src="scope.row.picture"  width="150">            
            </template>     
           </el-table-column> 
           
           <el-table-column :label="t('product.isgrounding')" align="center" prop="isgrounding" v-if="isMerchandiser">
           <template #default="scope">
              <el-switch
                 v-model="scope.row.isgrounding"
                 class="ml-2"
                 inline-prompt
                 style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;"
                 active-text="上架"
                 inactive-text="下架"
                 active-value="1"
                 inactive-value="0"
                 :before-change="()=>switchBeforeChange(scope.row)"
               />
           </template>
           </el-table-column>
           
           <el-table-column :label="t('product.isgrounding')" align="center" prop="isgrounding" v-if="!isMerchandiser">
            <template #default="scope">
              <el-tag   v-if="scope.row.isgrounding==='1'">上架</el-tag>
              <el-tag effect="dark" type="danger" v-else>下架</el-tag> 
            </template>
           </el-table-column>
           
           <el-table-column :label="t('common.createTime')" align="center" prop="createTime" />
          
           <el-table-column v-if="isMerchandiser" :label="t('common.operate')" width="250" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                 <el-button link type="primary" icon="icon-edit" @click="handlerUpdate(scope.row)" >{{t('common.modi')}}</el-button>
                 <el-button link type="primary" icon="icon-edit" @click="handlerCopy(scope.row)" >一键复制</el-button>
              </template>
           </el-table-column>
        </el-table>
          
         <el-pagination
              v-if="total>0"
              v-model:current-page="queryParams.page"
              v-model:page-size="queryParams.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              small="small"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
      
      
      
      
    </div>
  </div>
</template>

<script setup>
  import { ref} from 'vue'
  import { Plus,EditPen } from '@element-plus/icons-vue'  
  import { ElMessage} from 'element-plus'
  import { useRouter } from 'vue-router';
  import store from '@/store/index.js'
  //定义国际化的语言的文件
  import { useI18n } from 'vue-i18n';
  const { t } = useI18n();
  //路由
  const router = useRouter();
   
  //自定义组件
  import DivItem from '@/components/DivItem/index.vue'
  import ItemEdit from '@/components/DivItem/edit.vue'
  
  
 
  //组合式函数(代码重复的问题)
  import { usePage } from '@/composables/PageComp.js'
  
  import {dataApi, addApi, updateApi ,findByIdApi, upordownApi,priceChangeApi,stockChangeApi, batchUpOrDownApi} from '@/api/product.js'
  import {dataApi as categoryDataApi} from '@/api/categoryclass.js'

  //图片上传地址
  const imageUploadUrl =ref(process.env.VUE_APP_BASE_API+'/api/upload/image')
  const { proxy } = getCurrentInstance(); 

  
  //通用数据必须要有的
  const reactiveObject = ref({
     dataApi: dataApi,
     addApi: undefined,
     updateApi: undefined,
     findByIdApi: undefined,
     removeApi: undefined,
     proxy: proxy,
     //这里要变，主键名称
     primaryKey: 'id'
    }); 
  
  //分页查询
  const { loading, total,rows ,queryParams,autoExecute,selectionRows,ids,single,multiple , handleQuery, resetQuery, handleSizeChange , handleCurrentChange, getList,handleSelectionChange }=usePage(reactiveObject)

  //自己的定义额外参数
  const data = reactive({
    header: {
      'Authorization': store.getters['user/accessToken']
    },
    //分类列表
    categoryList: [],
    //是否显示修改效果
    showMoneyEdit:[],
    //修改前的价格，还原数据用
    oldPrice: [],
    //是否显示库存修改效果
    showStockEdit:[],
    //修改前的库存，还原数据用
    oldStock: []
  });
  
  ///自己的定义额外参数,用来使用的
  const { header, categoryList, showMoneyEdit, oldPrice,showStockEdit,oldStock} = toRefs(data);
  //选项卡
  const activeName = ref('all')
  
  function handleClick (tab, event) {
    const name= tab.props.name
    if(name==='all'){
      queryParams.value.isgrounding=undefined
    }else if(name==='up'){
       queryParams.value.isgrounding='1'
    }else if(name==='down'){
       queryParams.value.isgrounding='0'
    }
    handleQuery()
  }


   function switchBeforeChange(row){ 
     return new Promise((resolve) => {
      let msg=''
       //当前是上架状态
       if(row.isgrounding==='1'){
          msg='确定要下架该商品吗?'
       }else{
          msg='确定要上架该商品吗?'
       }

      ElMessageBox.confirm(msg,'询问',
         {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'danger',
         }
       ).then(() => {
           //更新数据库
           const data={ id: row.id}
           if(row.isgrounding==='1'){
             data.isgrounding= '0'
           }else{
              data.isgrounding='1'
           }
           upordownApi(data).then(resp=> {
              return resolve(true)
           }).catch(e=> {
              return resolve(false)
           })
         })
         .catch(() => {
            return resolve(false)
       })

     })

   }

   // 取消价格编辑操作
   function showMoneyInput(index, price){
     //如果有价格，先记录价格，说明准备要编辑价格了
     if (price) {
         oldPrice.value[index] = price;
     }else{
       //还原值，showMoneyEdit.value[index]=true,代表修改保存后的效果， false取消修改，就要还原值
       if(!showMoneyEdit.value[index]){
        //还原值
         rows.value[index].price= oldPrice.value[index];
       }
       //删除临时数据
       oldPrice.value.splice(index,1); 
     }
     // 使得价格修改框出现
     let arr = [...showMoneyEdit.value]; 
     //判断arr数组中是否存在当前下标，如果存在就设定为false，
     arr[index] = !arr[index];
     showMoneyEdit.value = arr;
   }
    
    // 修改价格确保操作
   function changeItemPrice(row, index) {
      if (row.price) {
          const price= parseFloat(row.price);
          if(price<0){
             ElMessage.error('商品价格不能小于0')
             return;
          }          
        
        
          let data = {
              id: row.id,
              price: price.toFixed(1)
          }
          priceChangeApi(data).then(res => { 
              ElMessage({ message: '价格更改成功', type: 'success'})
               
              //取消编辑样式
              showMoneyInput(index);  
              
          }).catch(err => {
          });
      } else {
         ElMessage.error('商品价格不能小于0')
      }
   }

   // 取消编辑库存操作
   function showStockInput(index, value){
     //如果有价格，先记录价格，说明准备要编辑价格了
     if (value) {
         oldStock.value[index] = value;
     }else{
       //还原值，showStockEdit.value[index]=true,代表修改保存后的效果， false取消修改，就要还原值
       if(!showStockEdit.value[index]){
        //还原值
         rows.value[index].num= oldStock.value[index];
       }
       //删除临时数据
       oldStock.value.splice(index,1); 
     }
     
     // 使得价格修改框出现
     let arr = [...showStockEdit.value]; 
     //判断arr数组中是否存在当前下标，如果存在就设定为false，
     arr[index] = !arr[index];
     showStockEdit.value = arr;
   }

   // 修改库存保存操作
   function changeItemStock(row, index) {
      if (row.num) {
          const stock= parseInt(row.num);
          if(stock<-1){
             ElMessage.error('商品库存不能小于-1')
             return;
          }          
        
        
          let data = {
              id: row.id,
              num: stock
          }
          stockChangeApi(data).then(res => { 
              ElMessage({ message: '库存更改成功', type: 'success'})               
              //取消编辑样式
              showStockInput(index);                
          }).catch(err => {
          });
      } else {
         ElMessage.error('商品库存不能为空')
      }
   }

  //计算属性
  const isMerchandiser = computed(() => {
    console.log( store.getters['user/permissions']);
    const pres=store.getters['user/permissions']
    if(pres && pres.length>0){
      return pres.includes('merchandiser')
    }
    return false;
  });
    
  //查询商品分类
  function fetchCategoryList(){
    const params={page:1,size:1000}
    categoryDataApi(params).then(resp=> {
      categoryList.value= resp.data.rows
    })
  }     

  //如果是商家
  if(isMerchandiser){
    fetchCategoryList()
  }
  
  //新增商品(打开新的路由地址，不要使用对话框)
  function handleAdd(){
    router.push({ path: '/product-edit' })
  }
  
  //编辑商品
  function handlerUpdate(row){
    router.push({ path: '/product-edit/'+row.id })
  }
  
  function tableSort(cols){
    const field= cols.prop
    const order= cols.order==='descending'? 'desc' : 'asc'
    
    //后端排序字段
    queryParams.value.field=field
    //排序的方式
    queryParams.value.order=order
    //从第一页开始重新查询
    handleQuery();
  }
  
  //批量上架
  function handlerUp(){
    //判断所选中的项目是有下架的产品
    const resultArr=selectionRows.value.filter(p=> p.isgrounding==='0');
    if(resultArr.length===0){
       ElMessage.error('选中的商品没有下架状态，不能进行上架操作')
      return;
    }    
    ElMessageBox.confirm('确定要上架选中的商品吗?','询问',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'danger',
       }
     ).then(() => {
         //更新数据库 
         const ids=resultArr.map(p=>p.id);
          batchUpOrDownApi(ids,'1').then(resp=>{
              ElMessage({ message: '批量上架商品成功', type: 'success'}) 
              //重新查询
              getList()
          })
       })
       .catch(() => { 
         proxy.$refs.tableRef.clearSelection()
      })    
  }
  
  //批量下架
  function handlerDown(){
    //判断所选中的项目是有上架的产品
    const resultArr=selectionRows.value.filter(p=> p.isgrounding==='1');
    if(resultArr.length===0){
       ElMessage.error('选中的商品没有上架状态，不能进行下架操作')
      return;
    }
    
    ElMessageBox.confirm('确定要下架选中的商品吗?','询问',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'danger',
       }
     ).then(() => {
         //更新数据库
       const ids=resultArr.map(p=>p.id);
        batchUpOrDownApi(ids,'0').then(resp=>{
            ElMessage({ message: '批量下架商品成功', type: 'success'}) 
            //重新查询
            getList()
        })
        
       })
       .catch(() => { 
         proxy.$refs.tableRef.clearSelection()
      })
  }
  
  //一键复制
  function handlerCopy(row){
     router.push({ path: '/product-copy/'+row.id })
  }
  
</script>

<style>
  .ml-2{
    width: 80px;
  }
 .ml-2 .el-switch__core{
   width:100%;
 }
</style>
<style scoped>
  .demo-tabs{
    padding:15px;
  }
  
  .flavorBox .flavor {
       border: solid 1px #dfe2e8;
       border-radius: 3px;
       padding: 15px;
       background: #fafafb;
     }
     .flavorBox .flavor .title {
       color: #606168;
     }
  
     .flavor .el-autocomplete {
        width: 150px;
     }
  
     .flavorBox .flavor .cont .labItems {
       display: block;
       border-radius: 3px;
       border: solid 1px #d8dde3;
       background: #fff;
       padding: 0 5px;
       margin-left: 10px;
       margin-top: 10px;
     }
  
    .flavorBox .flavor .cont .labItems2 {
      border-radius: 3px;
      min-height: 39px;
      margin-left: 10px;
       background: #fff;
       line-height: 26px;
       padding-top: 3px;
    }
  
     .flavorBox .flavor .cont  .delFlavor {
       display: inline-block;
       padding: 0 10px;
       color: #f19c59;
       cursor: pointer;
       float: right;
     }
  
     .flavorBox .flavor .cont {
       margin: 10px 0;
       padding: 10px;
       background-color: #fff;
     }
     .flavorBox .title   .kwbq{
        margin-left: 45px;
     }
  
</style>
